package vn.candyapp.qlct.fragment;

import vn.candyapp.qlct.R;
import vn.candyapp.qlct.adapter.ThongKeAdapter;
import vn.candyapp.qlct.item.KieuTKGiaoDich;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
import android.widget.Spinner;

public class TabThongKe extends BaseFragment {


	public static TabThongKe newInstance() {
		TabThongKe f = new TabThongKe();
		return f;
	}
	
	private ExpandableListView listViewThongKe;
	private Spinner spinnerChoose;
	private ThongKeAdapter tkAdapter;
	
	private String[] timeRange = new String[] { "TUẦN NÀY", "THÁNG NÀY", "NĂM NAY" };
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = inflater.inflate(R.layout.tab_thongke, container, false);
		initWidgets(v);
		addEvents();
		return v;
	}

	private void initWidgets(View v) {
		spinnerChoose = (Spinner) v.findViewById(R.id.spinChoose);
		listViewThongKe = (ExpandableListView) v.findViewById(R.id.elv_thong_ke);
		ArrayAdapter<String> spinnAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, timeRange);
		spinnAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		spinnerChoose.setAdapter(spinnAdapter);
		tkAdapter = new ThongKeAdapter(getActivity());
		tkAdapter.load(KieuTKGiaoDich.TUANNAY, new Runnable() {
			
			@Override
			public void run() {
				listViewThongKe.setAdapter(tkAdapter);
				listViewThongKe.expandGroup(0);
			}
		});
	}
	
	private void addEvents() {
		spinnerChoose.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
		
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				
				final Runnable run = new Runnable() {
					
					@Override
					public void run() {
						tkAdapter.notifyDataSetChanged();
					}
				};
				
				switch (position) {
					case 0:
						tkAdapter.load(KieuTKGiaoDich.TUANNAY, run);
						break;
					case 1:
						tkAdapter.load(KieuTKGiaoDich.THANGNAY, run);
						break;
					case 2:
						tkAdapter.load(KieuTKGiaoDich.NAMNAY, run);
						break;
					default:
						tkAdapter.load(KieuTKGiaoDich.TUANNAY, run);
						break;
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
	}
	
	@Override
	public void onRefresh() {
		tkAdapter.load(KieuTKGiaoDich.TUANNAY, new Runnable() {
			
			@Override
			public void run() {
				tkAdapter.notifyDataSetChanged();
			}
		});
	}
}
